import { getImageCode, authorizations } from '@/services/login'
import Cookie from '@/utils/cookie'
import { history } from 'umi'
import Store from '@/utils/store'
import { TokenKey } from '@/utils/auth'

export default {
  namespace: 'loginModel',
  state: {
    captchaData: {
      captcha_key: '',
      captcha_image_content: ''
    }
  },
  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    }
  },
  effects: {
    // 获取验证码
    *getCaptCha(action, { put, call, select }) {
      const data = {
        captchaData: yield call(getImageCode)
      }
      yield put({ type: 'save', payload: data })
    },
    // 登录
    *login({ payload }, { put, call, select }) {
      const { loginModel: loginModelState } = yield select()
      const { username, password, captcha } = yield payload
      const verification_key = loginModelState.captchaData.captcha_key
      const data = yield call(authorizations, {
        verification_code: captcha,
        verification_key,
        username,
        password
      })
      // 储存token
      yield Cookie.set(TokenKey, `${data.meta.token_type} ${data.meta.access_token}`)
      // 本地缓存登录信息
      yield Store.saveLocal('loginInfoSMP', data)
      // 储存用户信息
      delete data.meta
      yield put({
        type: 'user/updateUserInfo',
        payload: data
      })
      history.push('/index')
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/login') {
          dispatch({
            type: 'getCaptCha'
          })
        }
      })
    }
  }
}
